<template>
  <div>
    <van-search v-model="value" placeholder="请输入搜索关键词" @input="searchProducts"  style="position: sticky;top: 0;"/>
    <div class="container">
      <!-- 动态渲染侧边栏 -->
      <div class="sidebar" style="background-color: #fafafa;top: 54px;">
        <van-sidebar v-model="activeKey">
          <van-sidebar-item
            v-for="category in categoryList"
            :key="category.categoryId"
            :title="category.name"
            @click="loadProducts(category.categoryId)"
          />
        </van-sidebar>
      </div>

      <!-- 动态渲染商品内容 -->
      <div class="content" style="background-color: white;">
        <div v-if="filteredProducts.length > 0">
          <ul class="product-list">
            <li class="product-item" v-for="product in filteredProducts" :key="product.productId">
              <img :src="product.imgUrl" alt="" class="product-image">
              <div class="product-info">
                <p class="product-name">{{ product.masterName }}</p>
              </div>
            </li>
          </ul>
        </div>
        <div v-else>
          <p>暂无商品数据</p>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  components: {
    Footer
  },
  data() {
    return {
      activeKey: 0, // 当前激活的标签索引
      categoryList: [], // 存储从接口获取的分类数据
      products: [], // 存储当前分类的商品数据
      filteredProducts: [], // 存储筛选后的商品数据
      value: '', // 搜索关键词
    };
  },
  watch: {
    // 监听路由参数变化，重新加载商品数据
    '$route.params.categoryId'(newCategoryId) {
      this.loadProducts(newCategoryId);
    }
  },
  mounted() {
    this.fetchCategories().then(() => {
      const categoryId = this.$route.params.categoryId; // 获取路由参数中的categoryId
      if (categoryId) {
        this.loadProducts(categoryId); // 根据categoryId加载商品数据
        this.activeKey = this.categoryList.findIndex(category => category.categoryId === parseInt(categoryId)); // 设置当前激活的分类
      }
    });
  },
  methods: {
    async fetchCategories() {
      try {
        const response = await fetch("http://43.136.85.99:3003/category/all");
        const data = await response.json();
        if (data.code === 666) {
          this.categoryList = data.list; // 将接口返回的分类数据存储到 categoryList
          if (this.categoryList.length > 0) {
            this.activeKey = 0; // 默认激活第一个分类
          }
        } else {
          console.error("Failed to fetch categories:", data.msg);
        }
      } catch (error) {
        console.error("Error fetching categories:", error);
      }
    },
    async loadProducts(categoryId) {
      try {
        const response = await fetch(`http://43.136.85.99:3003/product/list?categoryId=${categoryId}`);
        const data = await response.json();
        if (data.code === 666) {
          this.products = data.list; // 将接口返回的商品数据存储到 products
          this.filteredProducts = data.list; // 初始化筛选后的商品数据
        } else {
          console.error("Failed to fetch products:", data.msg);
        }
      } catch (error) {
        console.error("Error fetching products:", error);
      }
    },
    searchProducts() {
      // 根据搜索关键词筛选商品
      if (this.value.trim() === '') {
        this.filteredProducts = this.products; // 如果搜索框为空，显示所有商品
      } else {
        this.filteredProducts = this.products.filter((product) => {
          // 检查商品名称是否包含搜索关键词
          return product.masterName.toLowerCase().includes(this.value.toLowerCase());
        });
      }
    },
  },
};
</script>

<style>
.container {
  display: flex;
  width: 100%;
  height: 100vh; /* 设置容器高度为视口高度 */
}

.sidebar {
  position: fixed; /* 侧边栏固定定位 */
  top: 0;
  left: 0;
  width: 80px; /* 侧边栏宽度 */
  height: 100%; /* 侧边栏高度为视口高度 */
  overflow-y: auto; /* 侧边栏内容超出时可以滚动 */
  margin-bottom: 50px;
}

.content {
  flex: 1; /* 右侧内容占据剩余空间 */
  padding: 10px;
  margin-left: 80px; /* 右侧内容与侧边栏的间距 */
  overflow-y: auto;
  margin-bottom: 50px; /* 右侧内容可以滚动 */
}

.product-list {
  padding: 0;
  list-style: none;
  display: flex;
  flex-wrap: wrap;
}

.product-item {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  flex-grow: 1;
  font-size: 12px;
  padding: 5px;
  width: 100px;
}

.product-image {
  height: 90px;
  width: 90px;
  margin-bottom: 5px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 12px;
  margin: 0;
}
</style>